<?php


namespace app\common\model;


use think\Db;
use think\Model;
use traits\model\SoftDelete;

class ShopModel extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'wanlshop_shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 店铺默认头像
    protected $shop_avatar = '/assets/img/shop.png';

    // 店铺展示页默认模块数
    protected $shop_show_location_num = 6;


    /**
     * 获取入驻申请信息
     */
    public function getApplyInfo($user_id): array
    {
        try {
            $row = model('app\index\model\wanlshop\Auth')->where(['user_id' => $user_id])->find();
            if ($row) {
                if ($row->verify == 2) {
                    throw new \Exception('申请审核中', 41002);
                }
                if ($row->verify == 3) {
                    throw new \Exception('申请已通过', 41003);
                }
                if ($row->verify == 4) {
                    throw new \Exception('申请已驳回', 41004);
                }
            }

            return [
                'code' => 200,
                'msg' => '暂无申请信息',
                'data' => []
            ];
        } catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 提交店铺入驻信息
     *
     * @param string|int $state 店铺类型:0=个人,1=企业,2=旗舰
     * @param string $shopname 店铺名称
     * @param string $name 企业名/姓名
     * @param string $number 统一信用/身份证号
     * @param string $mobile 电话
     * @param string $image 证件图片
     * @param string $wechat 微信号
     * @param string $trademark 商标证书
     * @param string $avatar 店铺头像
     * @param string $bio 店铺简介
     * @param string $content 店铺介绍
     * @param string $city 省市
     * @param string $certificate 转账证明
     */
    public function apply($params, $user_id): array
    {
        extract($params);
        Db::startTrans();
        try {
            $row = model('app\index\model\wanlshop\Auth')->where(['user_id' => $user_id])->find();
            if ($row) {
                if ($row->verify == 2) {
                    throw new \Exception('申请审核中,请勿重复提交', 41002);
                }
                if ($row->verify == 3) {
                    throw new \Exception('申请已通过,请勿重复提交', 41003);
                }
            }

            $config = get_addon_config('wanlshop');
            $verify = $config['config']['store_audit'] == 'N' ? 3 : 2;

            // 更新提交信息
            $params['user_id'] = $user_id;
            $params['verify'] = $verify;
            model('app\index\model\wanlshop\Auth')->save($params);

            // 自动审核
            if ($config['config']['store_audit'] == 'N') {
                // 新增店铺
                $shop = model('app\index\model\wanlshop\Shop');
                $shop->user_id = $user_id;
                $shop->state = $params['state'];
                $shop->shopname = $params['shopname'];
                $shop->avatar = $params['avatar'];
                $shop->bio = $params['content'];
                $shop->description = $params['bio'];
                $shop->city = $params['city'];
                $shop->verify = $verify;
                // 新增店铺配置
                if ($shop->save()) {
                    $config = model('app\index\model\wanlshop\ShopConfig');
                    $config->shop_id = $shop->id;
                    $config->save();
                }
            }

            Db::commit();
            return [
                'code' => 200,
                'msg' => '提交成功',
                'data' => []
            ];
        } catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 获取展示页数据
     */
    public function getShopShowData($user_id): array
    {
        try {
            $data = [];
            $show_location_data = model('app\admin\model\shop\ShowLocation')
                ->with(['shop' => function ($q) {
                    $q->field('id,user_id,shopname,avatar,isself');
                }])
                ->field('id,shop_id')
                ->order('id', 'asc')
                ->select();
            $middle = [];
            foreach ($show_location_data as $row) {
                if(count($data) == $this->shop_show_location_num) {
                    break;
                }
                if ($row->shop) {
                    $row->shop->avatar = cdnurl($row->shop->avatar, true);
                }else{
                    $row->shop = [
                        'shopname' => '',
                        'avatar' => cdnurl($this->shop_avatar, true),
                    ];
                }
                $middle[] = $row;
                if ($row->id % 20 == 0) {
                    $data[]['shop'] = $middle;
                    $middle = [];
                }
            }
            $banner_data = model('app\admin\model\shop\ShowLocationBanner')
                ->field('id,title,image,path')
                ->where(['status' => '1'])
                ->order('weigh', 'asc')
                ->select();
            $num = ceil(count($banner_data) / $this->shop_show_location_num);
            for ($i = 0; $i < count($data); $i++) {
                $data[$i]['banner'] = [];
                $in_num = 0;
                foreach ($banner_data as $key => $val){
                    $val['image'] = cdnurl($val['image'], true);
                    $data[$i]['banner'][] = $val;
                    unset($banner_data[$key]);
                    $in_num += 1;
                    if($in_num == $num) {
                        break;
                    }
                }
            }

            return [
                'code' => 200,
                'msg' => '提交成功',
                'data' => $data
            ];
        } catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 提交店铺展示位入驻信息
     *
     * @ApiMethod (POST)
     * @param int $show_id 展示位ID
     * @param string $certificate 转账证明
     */
    public function applyShopShowLocation($params, $user_id): array
    {
        extract($params);
        Db::startTrans();
        try {
            $shop = model('app\index\model\wanlshop\Shop')
                ->where([
                    'user_id' => $user_id,
                    'verify' => '3',
                    'status' => 'normal',
                ])
                ->whereNull('deletetime')
                ->find();
            if (!$shop) {
                throw new \Exception('未找到此商家', 41005);
            }

            $shop_show_location = model('app\admin\model\shop\ShowLocation')->get($show_id);
            if($shop_show_location && !empty($shop_show_location->shop_id)) {
                throw new \Exception('提交失败,该展示位已有商家入驻', 41008);
            }

            $row = model('app\admin\model\shop\ShowLocationApply')
                ->where([
                    'user_id' => $user_id,
                    'shop_id' => $shop->id,
                    'show_id' => $show_id,
                ])
                ->find();
            if ($row) {
                if ($row->status == 0) {
                    throw new \Exception('申请审核中,请勿重复提交', 41006);
                }
                if ($row->status == 1) {
                    throw new \Exception('申请已通过,请勿重复提交', 41007);
                }
            }else{
                $row = model('app\admin\model\shop\ShowLocationApply');
            }
            $row->user_id = $user_id;
            $row->shop_id = $shop->id;
            $row->show_id = $show_id;
            $row->certificate = $certificate;
            $row->status = 0;
            $row->save();

            Db::commit();
            return [
                'code' => 200,
                'msg' => '提交成功',
                'data' => []
            ];
        } catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }

}